package com.pengshun.modules.api.pay.service;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * @author luoligang
 */
public class HttpRequest {


    public static String post(String url, String xml, boolean ssl,String mchId,String certPath) {
        CloseableHttpClient client;
        String responseText = "";
        CloseableHttpResponse response = null;
        if (ssl){
            client = getHttpClient(mchId,certPath);
        }else{
            client = HttpClients.createDefault();
        }
        try {
            HttpPost method = new HttpPost(url);
            if (xml != null) {
                method.setEntity(new StringEntity(xml, "UTF-8"));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity,"UTF-8");
            }
        } catch (Exception e) {
            System.err.println("post: "+e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                System.err.println("post: "+e);
            }
        }
        return responseText;
    }

    private static CloseableHttpClient getHttpClient(String mchId, String certPath){
        CloseableHttpClient client = null;
        try{
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            File file = new File(certPath);
            FileInputStream instream = new FileInputStream(file);
            keyStore.load(instream, mchId.toCharArray());
            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, mchId.toCharArray())
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            client = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
        }catch(Exception e){
            System.err.println("post: "+e);
        }
        return client;
    }
}
